<?php

namespace App\Http\Controllers\Api\V1\Manager\User;

use App\Http\Controllers\Controller;
use App\Models\UserManager;
use App\Models\UserManagerRole;
use App\Services\Manager\LogService;
use Illuminate\Http\Request;

class RoleController extends Controller
{
    /**角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $shopId = $request->SHOPID;
        $pageSize = $request->pageSize;
        $sql = UserManagerRole::select('roleId', 'roleName', 'resources')->where('shopId', $shopId);;
        $role = $sql->orderByDesc('updateTime')->paginate($pageSize)->toArray();
        $data['roleList'] = $role['data'];
        $data['totalNum'] = $role['total'];
        return $this->apiResponse($data);
    }

    /**
     * 角色详情
     * @param $roleId
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function show($roleId)
    {
        $data = UserManagerRole::where('roleId', $roleId)->first();
        return $this->apiResponse($data);
    }


    /**
     * 角色新增修改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $managerId = $request->MANAGERID;
        $roleId = $request->roleId;
        $data = $request->only('roleName', 'resources');
        $shopId = $request->SHOPID;
        if ($roleId) {
            $roleName = UserManagerRole::where('roleId',$roleId)->value('roleName');
            UserManagerRole::where('roleId', $roleId)->update($data);
            $yuyan = "修改了[".$roleName."]角色为[".$data['roleName']."]";
        } else {
            $time = date("Y-m-d H:i:s");
            $data['createTime'] = $time;
            $data['shopId'] = $shopId;
            UserManagerRole::insert($data);
            $yuyan = "新增了[".$data['roleName']."]角色";
        }
        $logService  = new LogService();
        $logService->addLog($managerId,$shopId,"角色新增修改",$yuyan);
        return $this->apiResponse(true);
    }

    /**
     * 角色删除
     * @param $roleId
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(Request $request,$roleId)
    {
        $managerId = $request->MANAGERID;
        $shopId = $request->SHOPID;
        $logService  = new LogService();
        $num = UserManager::where('roleId',$roleId)->count();
        if($num){
            return $this->apiResponse('',[
                'errorCode' => "30035",
                'errorMessage' => '有['.$num.']名员工在使用,请勿删除'
            ]);

        }
        $roleName = UserManagerRole::where('roleId',$roleId)->value('roleName');
        $logService->addLog($managerId,$shopId,"角色删除","删除了[".$roleName."]角色");
        UserManagerRole::destroy($roleId);
        return $this->apiResponse(true);
    }
}
